//
//  YFNetworkingService.m
//  SquashSpark
//
//  Created by Coollang on 2017/11/4.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFNetworkingService.h"
#import <YTKNetwork/YTKNetwork.h>
#import "AppDelegate+extension.h"

@interface YFNetworkingService()<YTKChainRequestDelegate,UIAlertViewDelegate>

@end
@implementation YFNetworkingService {
    __weak FUIAlertView *logoutAlert;
}
+ (instancetype)sharedInstance
{
    static id sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

+ (QNUploadManager *)qNUploadManager {
    static QNUploadManager *_qn_UpManager = nil;
    if (_qn_UpManager == nil) {
        QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
            // 华南地区
            builder.zone = [QNFixedZone zone2];
        }];
        _qn_UpManager = [[QNUploadManager alloc] initWithConfiguration:config];
    }
    return _qn_UpManager;
}
-(void)configureBaseUrl {
    YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
    
    config.baseUrl = kBaseUrl;
    [self setupRequestFilters];
    // 配置缓存
    if ([YFUserDefaults shouldAutoLogin]) {
        [self setUpRequestCacheFiltersWithUserId:[YFUserDefaults lastLoginID]];
    }
    // 开启网络监控
    [YFCheckNetworkStatus shareInstance];
    [[YTKNetworkAgent sharedAgent] setValue:[NSSet setWithObjects:
                                             @"application/json",
                                             @"text/html",
                                             @"text/plain",
                                             @"text/javascript",
                                             @"image/jpeg",
                                             @"image/png",
                                             @"application/octet-stream",
                                             @"text/json",
                                             nil]
                                 forKeyPath:@"jsonResponseSerializer.acceptableContentTypes"];
}
- (void)setupRequestFilters {
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
    YFUrlArgumentsFilter *urlFilter = [YFUrlArgumentsFilter filterWithArguments:@{@"version": appVersion}];
    [config addUrlFilter:urlFilter];
}

// 配置缓存
- (void)setUpRequestCacheFiltersWithUserId:(NSString *)userId {
    YTKNetworkConfig *config = [YTKNetworkConfig sharedConfig];
    [config clearCacheDirPathFilter];
    YFUrlCacheDirPathFilter *cacheFilter = [YFUrlCacheDirPathFilter filterWithArguments:userId];
    [config addCacheDirPathFilter:cacheFilter];
}

- (void)cancelRequest:(YFBaseRequest *)request{
    [request stop];
}

//一般的请求
-(void)sendRequest:(YFBaseRequest *)request
          callback:(CRSNetworkingServiceBlock)block {
    
    [request startWithCompletionBlockWithSuccess:^(YTKBaseRequest *req) {
        NSLog(@"responseJsonString:%@",request.responseString);
        NSString * result = req.responseJSONObject[@"ret"];
        // 错误处理
        NSLog(@"%@",req.responseObject[@"errDesc"]);
        if (result.integerValue == WebRespondTypeSuccess || [result isEqualToString:@"200"]){
            if (block){ block(YES,req,nil);}
        }else {
            NSError *error = [request disposeRequestErrorWithRet:result];
            request.reqError = error;
            if (block){ block(NO,req,error);}
            [self errorAlertDispose:error];
        }
    } failure:^(YTKBaseRequest *req) {
        NSError *error;
        if([YFCheckNetworkStatus isReachable] == NO){
            error = [YFNetError creatErrorWithRet:WebRespondTypeNotReachable];
        }else {
            if ([[req.responseObject allKeys] containsObject:@"ret"]){
                error = [request disposeRequestErrorWithRet:req.responseJSONObject[@"ret"]];
            }else {
                // 这里的错误处理情况要复杂一点,要处理 404 501 等系统错误
                if (req.response.statusCode == WebRespondTypeServiceError || req.response.statusCode == WebRespondTypeServiceError404) {
                    error = [YFNetError creatErrorWithRet:req.responseStatusCode];
                }else {
                    error = req.error;
                }
            }
        }
        request.reqError = error;
        [self errorAlertDispose:error];
        if (block) {
            block(NO,req,error);
        }
    }];
}

- (void)errorAlertDispose:(NSError *)error {
    if (error.code == WebRespondTypeNotLogin || error.code == WebRespondTypeTokenInconformity) {
        // 登录失效
        if (logoutAlert == nil) {
            logoutAlert = [FUIAlertView alertWithTitle:@"Prompt" message:NSLocalizedString(@"Log on invalid,please log in again", nil) cancelTitle:@"No" confirmTitle:@"Yes"];
            logoutAlert.onOkAction = ^{
                [AppDelegate logoutWithShowLoginVC:YES];
            };
        }
        if (logoutAlert.visible == NO) {
           [logoutAlert show];
        }
    }
}

//并发请求
-(void)sendBatch:(NSArray *)requestArray
        callback:(CRSNetworkingServiceBlock)block {
    YTKBatchRequest *batchRequest = [[YTKBatchRequest alloc] initWithRequestArray:requestArray];
    [batchRequest startWithCompletionBlockWithSuccess:^(YTKBatchRequest *batchRequest) {
        if (block){
            block(YES,batchRequest,nil);
        }
    } failure:^(YTKBatchRequest *batchRequest) {
        if (block){
            block(NO,batchRequest,[YFNetError creatErrorWithRet:WebRespondTypeOther]);
        }
    }];
}

- (void)updateAppRequest{
    /**获取程序的版本号*/
    NSString *version = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    [mgr.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil]];
    [mgr POST:@"https://itunes.apple.com/cn/lookup?id=1332249612" parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        if ([responseObject[@"resultCount"] integerValue] == 1) {
            NSDictionary *infoDic = responseObject[@"results"][0];
            NSString *appstoreVersion = infoDic[@"version"];
            if ([version compare:appstoreVersion options:NSCaseInsensitiveSearch] == -1) {//判断版本大小
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"NEW VERSION" message:@"Is There A New Version To Update" delegate:self cancelButtonTitle:@"CANCEL" otherButtonTitles:@"UPDATE", nil] ;
                alert.delegate = self;
                [alert show];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/squash-spark/id1332249612?l=zh&ls=1&mt=8"]]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/squash-spark/id1332249612?l=zh&ls=1&mt=8"]];
        }
    }
}

@end
